import 'package:app_router_demo/config/app_router.dart';
// import 'package:app_router_demo/customs/app_appbar.dart'; // This import is not used, can be removed if not used elsewhere
import 'package:app_router_demo/gen/app_images.dart';
import 'package:app_router_demo/pages/login/widget/gradient_button.dart';
import 'package:app_router_demo/providers/auth_provider.dart'; // This import is not directly used in this file's logic, can be removed if not used elsewhere
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:provider/provider.dart'; // This import is not directly used in this file's logic, can be removed if not used elsewhere

@RoutePage()
class LoginPhonePage extends StatefulWidget {
  const LoginPhonePage({super.key});

  @override
  State<LoginPhonePage> createState() => _LoginPhonePageState();
}

class _LoginPhonePageState extends State<LoginPhonePage> {
  final TextEditingController _phoneController = TextEditingController();
  bool _isButtonActive = false;

  @override
  void dispose() {
    _phoneController.removeListener(
      _updateButtonState,
    ); // Good practice to remove listener
    _phoneController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _phoneController.addListener(_updateButtonState);
  }

  void _updateButtonState() {
    setState(() {
      _isButtonActive = _phoneController.text.length >= 11;
    });
  }

  @override
  Widget build(BuildContext context) {
    // AuthProvider is not actively listened to or used for logic in this specific build method
    final authProvider = Provider.of<AuthProvider>(context);
    // debugPrint('LoginPhonePage build: isLoggedIn = ${authProvider.isLoggedIn}');

    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.black,
      body: GestureDetector(
        // <-- 添加 GestureDetector
        onTap: () {
          // 点击背景时，移除当前焦点，从而隐藏键盘
          FocusScope.of(context).unfocus();
        },
        child: Stack(
          children: [
            Positioned.fill(
              child: Image.asset(
                AppImages.VZ_DL_XKBG, // Replace with your actual image/video
                fit: BoxFit.cover,
              ),
            ),
            Positioned(
              top: MediaQuery.of(context).padding.top + 10,
              left: 16,
              child: IconButton(
                onPressed: () {
                  context.router.pop();
                },
                icon: Icon(Icons.arrow_back_ios, size: 24, color: Colors.white),
              ),
            ),
            SafeArea(
              child: Column(
                children: [
                  SizedBox(height: 52 + 44),
                  Container(
                    padding: EdgeInsets.only(left: 32, right: 32),
                    child: _buildLoginTopWidget(authProvider),
                  ),
                  Spacer(),
                  Container(
                    padding: EdgeInsets.only(left: 32, right: 32),
                    child: _buildLoginBottomWidget(),
                  ),
                  SizedBox(height: 32), // 底部留白
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoginTopWidget(AuthProvider authProvider) {
    return Column(
      children: [
        Text(
          "Login by phone number",
          style: TextStyle(
            color: Colors.white,
            fontSize: 24,
            fontWeight: FontWeight.w700,
          ),
        ),
        SizedBox(height: 8),
        Text(
          "we’ll send a verification code on this number",
          style: TextStyle(
            color: Color(0xff9797A1),
            fontSize: 13,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(height: 24),

        Container(
          height: 56,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            border: Border.all(
              color: Color.fromARGB(255, 156, 169, 233),
              width: 1,
            ),
          ),
          child: Row(
            children: [
              // 国家代码选择
              Row(
                children: [
                  Image.asset(
                    AppImages.VZ_VISTAR, // 需要添加中国国旗图片
                    width: 24,
                  ),
                  const SizedBox(width: 8),
                  const Text(
                    '+86',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(width: 3),
                  const Icon(Icons.arrow_drop_down, color: Colors.white),
                ],
              ),
              const SizedBox(width: 9),

              // 手机号输入
              Expanded(
                child: TextField(
                  controller: _phoneController,
                  keyboardType: TextInputType.phone,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                  ),
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: 'Phone number',
                    hintStyle: TextStyle(color: Color(0xff686877)),
                  ),
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly,
                    LengthLimitingTextInputFormatter(11),
                  ],
                ),
              ),
            ],
          ),
        ),

        SizedBox(height: 24),
        GradientContinueButton(
          isActive: _isButtonActive,
          onPressed:
              _isButtonActive
                  ? () async {
                    // 发送验证码
                    FocusScope.of(context).unfocus(); // 隐藏键盘
                    SmartDialog.showLoading();
                    bool success = await authProvider.sendVerificationCode(
                      _phoneController.text,
                      "62",
                    );

                    if (success) {
                      SmartDialog.dismiss();
                      // 发送成功，跳转到验证码页面
                      context.router.push(
                        LoginCodeRoute(
                          phoneNum: _phoneController.text,
                          countryCode: "62",
                        ),
                      );
                    } else {
                      SmartDialog.dismiss();
                      // 发送失败，显示提示
                      ScaffoldMessenger.of(
                        context,
                      ).showSnackBar(SnackBar(content: Text('发送验证码失败，请检查手机号')));
                    }
                  }
                  : null,
          text: 'Continue',
        ),
      ],
    );
  }

  Widget _buildLoginBottomWidget() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center, // 水平居中,
          children: [
            Container(height: 1, width: 62, color: Color(0xff676767)),
            SizedBox(width: 6),
            Text(
              "Or continue with",
              style: TextStyle(
                color: Color(0xff676767),
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(width: 6),
            Container(height: 1, width: 62, color: Color(0xff676767)),
          ],
        ),
        SizedBox(height: 32),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              onPressed: () {
                debugPrint('Back button pressed!');
                context.router.pop();
              },
              icon: Image.asset(AppImages.VZ_PPG, width: 44, height: 44),
            ),
            SizedBox(width: 12),
            IconButton(
              onPressed: () => {},
              icon: Image.asset(AppImages.VZ_PGG, width: 44, height: 44),
            ),
            SizedBox(width: 12),
            IconButton(
              onPressed: () => {},
              icon: Image.asset(AppImages.VZ_PFB, width: 44, height: 44),
            ),
            SizedBox(
              height: 44,
            ), // This SizedBox should probably be outside the Row or adjusted.
          ],
        ),
      ],
    );
  }
}
